package cn.hsw.component.auth.jwt;

import cn.hsw.component.auth.constant.AuthConstant;
import cn.hsw.component.core.enums.HttpEnum;
import cn.hsw.component.core.util.ResultUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 李子木
 */
public class JwtFilter extends BasicHttpAuthenticationFilter {

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {

        /*判断用户是否带有token 不带有直接跳过*/
        if(isLoginAttempt(request,response)){
            try{
                executeLogin(request,response);
            }catch (Exception e){
                /*这里处理异常*/
                HttpServletResponse hsr = (HttpServletResponse) response;
                hsr.setStatus(HttpStatus.OK.value());
                response.setContentType("application/json;charset=utf-8");
                try {
                    response.getWriter().write(JSONObject.toJSONString(ResultUtil.error(HttpEnum.FORBIDDEN.getCode(),e.getMessage())));
                } catch (IOException ioException) {
                    System.out.println("io exception");
                }
                return false;
            }
        }
        return true;
    }

    @Override
    protected boolean isLoginAttempt(ServletRequest request, ServletResponse response) {
        String token = ((HttpServletRequest) request).getHeader(AuthConstant.TOKEN_HEADER_NAME);
        String path = ((HttpServletRequest) request).getServletPath();
        if(path.startsWith(AuthConstant.PATH_PREFIX)){
            return false;
        }
        return StrUtil.isNotBlank(token);
    }

    @Override
    protected boolean executeLogin(ServletRequest request, ServletResponse response){
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String token = httpServletRequest.getHeader(AuthConstant.TOKEN_HEADER_NAME);
        token = JwtUtil.checkToken(token);
        JwtToken jwtToken = new JwtToken(token);

        getSubject(request, response).login(jwtToken);
        return true;
    }

    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        httpServletResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("Origin"));
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
        httpServletResponse.setHeader("Access-Control-Allow-Headers",
                httpServletRequest.getHeader("Access-Control-Request-Headers"));
        // 跨域时会首先发送一个option请求，这里我们给option请求直接返回正常状态
        if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpServletResponse.setStatus(HttpStatus.OK.value());
            return false;
        }
        return super.preHandle(request, response);
    }
}
